package com.example.shipload_e.update_tool;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.util.Log;

public class Tools {
	private final List<Map<String, Object>>	data	= new ArrayList<Map<String, Object>>();
	Map<String, Object>	                    item;

	public static String getCurrentVersion(Context context) throws NameNotFoundException {
		PackageManager manager = context.getPackageManager();
		String packageName = context.getPackageName();
		PackageInfo packageInfo = manager.getPackageInfo(packageName, 0);

		return packageInfo.versionName;
	}

	public static void installApk(String apkPath,Context context) {

		Intent intent = new Intent(Intent.ACTION_VIEW);
		Uri data = Uri.fromFile(new File(apkPath));

		String type = "application/vnd.android.package-archive";
		intent.setDataAndType(data, type);
		context.startActivity(intent);
	}

	class PInfo {
		private String	appname		= "";

		private double	versionCode	= 0;

	}

	public List<Map<String, Object>> listPackages(Context context) {
		ArrayList<PInfo> apps = getInstalledApps(false, context);
		final int max = apps.size();
		for(int i = 0;i < max;i++) {

			if(apps.get(i).appname.equals("RebootTimer")
			        || apps.get(i).appname.equals("VedioRecord_server")
			        || apps.get(i).appname.equals("船家宝") || apps.get(i).appname.equals("启动项管理")) {
				item = new HashMap<String, Object>();
				item.put(apps.get(i).appname, apps.get(i).appname);
				item.put("versionCode", apps.get(i).versionCode);
				data.add(item);
			}
		}
		Log.i("CCC", "JJ::" + data.toString());
		return data;
	}

	private ArrayList<PInfo> getInstalledApps(boolean getSysPackages,Context context) {
		ArrayList<PInfo> res = new ArrayList<PInfo>();
		List<PackageInfo> packs = context.getPackageManager().getInstalledPackages(0);
		for(int i = 0;i < packs.size();i++) {
			PackageInfo p = packs.get(i);
			if((!getSysPackages) && (p.versionName == null)) {
				continue;
			}
			PInfo newInfo = new PInfo();
			newInfo.appname = p.applicationInfo.loadLabel(context.getPackageManager()).toString();
			newInfo.versionCode = p.versionCode;
			res.add(newInfo);

		}
		return res;
	}

}
